/*     */ package com.yizhilu.os.image.util;
/*     */ 
/*     */ import com.google.gson.Gson;
/*     */ import com.google.gson.GsonBuilder;
/*     */ import com.yizhilu.os.core.service.cache.MemCache;
/*     */ import com.yizhilu.os.core.util.StringUtils;
/*     */ import java.io.*;
/*     */
/*     */
/*     */
/*     */
/*     */
/*     */
/*     */
/*     */ import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
/*     */ import java.util.HashMap;
/*     */ import java.util.Map;
/*     */ import javax.mail.internet.MimeUtility;
/*     */ import javax.servlet.http.HttpServletRequest;
/*     */ import javax.servlet.http.HttpServletResponse;
/*     */ import nl.bitwalker.useragentutils.Browser;
/*     */ import nl.bitwalker.useragentutils.OperatingSystem;
/*     */ import nl.bitwalker.useragentutils.UserAgent;

import static com.yizhilu.os.image.util.FileUtil.readInputStream;

/*     */
/*     */ public class FileDownloadUtil
/*     */ {
/*  27 */   private static MemCache memCache = MemCache.getInstance();
/*  28 */   private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
/*     */   public static final String LIBRARY_TYPE = "library";
/*     */   public static final String LECTURE_NOTES_TYPE = "lectureNotes";
/*     */ 
/*     */   public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File zipFile)
/*     */     throws Exception
/*     */   {
/*  39 */     String fileName = zipFile.getName();
/*  40 */     fileName = fileName(request, fileName.split("\\.")[0]);
/*     */ 
/*  42 */     response.setCharacterEncoding("UTF-8");
/*  43 */     response.setHeader("Content-type", "application/zip");
/*  44 */     response.setHeader("Content-disposition", "attachment;" + fileName + ".zip");
/*     */ 
/*  46 */     BufferedInputStream bis = null;
/*  47 */     BufferedOutputStream bos = null;
/*  48 */     OutputStream fos = null;
/*  49 */     InputStream fis = null;
/*  50 */     fis = new FileInputStream(zipFile.getPath());
/*  51 */     bis = new BufferedInputStream(fis);
/*  52 */     fos = response.getOutputStream();
/*  53 */     bos = new BufferedOutputStream(fos);
/*     */ 
/*  55 */     int bytesRead = 0;
/*  56 */     byte[] buffer = new byte[5120];
/*  57 */     while ((bytesRead = fis.read(buffer)) != -1) {
/*  58 */       bos.write(buffer, 0, bytesRead);
/*     */     }
/*  60 */     bos.flush();
/*  61 */     bis.close();
/*  62 */     fos.flush();
/*  63 */     fis.close();
/*     */   }
/*     */ 
/*     */   public static Object donwFile(HttpServletRequest request, Long userId, Long dataId, String fileName, String callback, Map<String, Object> resultMap, String donwType)
/*     */     throws IOException
/*     */   {
/*  87 */     String fileUrl = (String)resultMap.get("message");
/*  88 */     if ((fileUrl != null) && (!fileUrl.trim().endsWith(".zip")) && (!fileUrl.endsWith(".rar"))) {
/*  89 */       int l = fileUrl.lastIndexOf(".");
/*  90 */       fileUrl = fileUrl.substring(0, l) + ".pdf";
/*     */     }
/*  92 */     System.out.println("----------fileUrl:" + fileUrl);
/*  93 */     File _f = new File(FileUtil.rootpath + fileUrl);
/*     */ 
/*  95 */     System.out.println("------------------_f:" + _f);
/*  96 */     if (_f.exists()) {
/*  97 */       String zipPath = _f.getPath();
/*  98 */       File zipFile = null;
/*  99 */       if ((!fileUrl.trim().endsWith(".zip")) && (!fileUrl.endsWith(".rar"))) {
/* 100 */         if ((fileName != null) && (fileName.trim().length() > 0)) {
/* 101 */           if (fileName.length() > 16) {
/* 102 */             fileName = fileName.substring(0, 17);
/*     */           }
/* 104 */           int len = zipPath.lastIndexOf("/");
/* 105 */           if (len == -1) {
/* 106 */             len = zipPath.lastIndexOf("\\");
/*     */           }
/* 108 */           zipPath = zipPath.substring(0, len) + "/" + fileName + ".zip";
/*     */         } else {
/* 110 */           int len = zipPath.lastIndexOf(".");
/* 111 */           zipPath = zipPath.substring(0, len) + ".zip";
/*     */         }
/* 113 */         zipFile = FileUtil.doZip(_f.getPath(), zipPath);
/*     */       } else {
/* 115 */         zipFile = _f;
/*     */       }
/* 117 */       System.out.println(zipFile);
/* 118 */       String key = StringUtils.getRandomString(8) + "-" + System.currentTimeMillis();
/* 119 */       memCache.set(key, zipFile);
/* 120 */       resultMap = new HashMap();
/* 121 */       resultMap.put("success", Boolean.valueOf(true));
/* 122 */       resultMap.put("message", "下载验证成功");
/* 123 */       resultMap.put("entity", "/executeDownload?key=" + key + "&userId=" + userId + "&dataId=" + dataId + "&donwType=" + donwType);
/* 124 */       return callback + "(" + gson.toJson(resultMap) + ")";
/*     */     }
/* 126 */     System.out.println("donwLibrary()--文件不存在");
/* 127 */     resultMap.put("success", Boolean.valueOf(false));
/* 128 */     resultMap.put("message", "下载文件不存在");
/* 129 */     return callback + "(" + gson.toJson(resultMap) + ")";
/*     */   }
/*     */ 
/*     */   public static String fileName(HttpServletRequest request, String new_filename)
/*     */   {
/* 134 */     String userAgent = getUserAgent(request);
/* 135 */     String rtn = "filename=xteam";
/*     */     try {
/* 137 */       if (userAgent != null) {
/* 138 */         userAgent = userAgent.toLowerCase();
/*     */ 
/* 140 */         if (userAgent.indexOf("internet explorer") != -1) {
/* 141 */           rtn = "filename=\"" + URLEncoder.encode(new_filename, "utf-8") + "\"";
/*     */         }
/* 144 */         else if (userAgent.indexOf("opera") != -1) {
/* 145 */           rtn = "filename*=" + new_filename;
/*     */         }
/* 148 */         else if (userAgent.indexOf("safari") != -1) {
/* 149 */           rtn = "filename=" + new String(new_filename.getBytes("UTF-8"), "ISO8859-1") + "";
/*     */         }
/* 152 */         else if (userAgent.indexOf("chrome") != -1) {
/* 153 */           new_filename = new String(new_filename.getBytes("UTF-8"), "ISO8859-1");
/* 154 */           rtn = "filename=\"" + new_filename + "\"";
/*     */         }
/* 157 */         else if (userAgent.indexOf("firefox") != -1) {
/* 158 */           new_filename = MimeUtility.encodeText(new_filename, "UTF8", "B");
/* 159 */           rtn = "filename*=" + new_filename;
/*     */         }
/*     */       }
/*     */     } catch (Exception e) {
/* 163 */       e.printStackTrace();
/*     */     }
/* 165 */     return rtn;
/*     */   }
/*     */ 
/*     */   public static String getUserAgent(HttpServletRequest request) {
/* 169 */     String uabrow = request.getHeader("User-Agent");
/* 170 */     UserAgent userAgent = UserAgent.parseUserAgentString(uabrow);
/* 171 */     Browser browser = userAgent.getBrowser();
/* 172 */     OperatingSystem os = userAgent.getOperatingSystem();
/* 173 */     return browser.getName().toLowerCase() + ";" + os.getName().toLowerCase();
/*     */   }
    public static void  downLoadFromUrl(String urlStr,String fileName,String savePath) throws IOException{
        URL url = new URL(urlStr);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3*1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);
        //文件保存位置
        File saveDir = new File(savePath);
        if(!saveDir.exists()){
            saveDir.mkdir();
        }
        File file = new File(saveDir+File.separator+fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        if(fos!=null){
            fos.close();
        }
        if(inputStream!=null){
            inputStream.close();
        }
    }
    public static  byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }
}